import { axios } from '@/utils/axios';
import { action, makeAutoObservable } from 'mobx';
import { makePersistable } from 'mobx-persist-store';
import type { AiChatMessage, ThemeModeType } from './type';

export class ChatStores {
  count = 0;
  isHydrated = false;

  constructor() {
    makeAutoObservable(this);

    makePersistable(this, {
      name: 'ChatStores',
      properties: ['aiMessages', 'bgColor', 'theme', 'isLoading'],
      storage: window.localStorage,
    }).then(
      action(persistStore => {
        this.isHydrated = persistStore.isHydrated;
      })
    );
  }
  // ==================== AI 聊天内容管理 ====================
  aiMessages: AiChatMessage[] = [];
  getAiContent() {
    return this.aiMessages;
  }
  addContent(content: AiChatMessage) {
    this.aiMessages.push(content);
  }
  updateAiContent(index: number, newContent: string) {
    this.aiMessages[index].content += newContent;
  }
  bgColor: string = '';
  setBgColor(color: string) {
    this.bgColor = color;
  }
  clearContent() {
    this.aiMessages = [];
  }
  isLoading: boolean = false;
  setIsLoading(loading: boolean) {
    this.isLoading = loading;
  }
  theme: ThemeModeType = 'light';
  setTheme(mode: ThemeModeType) {
    this.theme = mode;
  }
  toggleTheme = () => {
    this.theme = this.theme === 'light' ? 'dark' : 'light';
  };
  async startChat(message: string, conversationIds?: { userId: string }) {
    const response = await axios.post<{ text: string }, { text: string }>(
      '/api/ask',
      {
        text: message,
        userId: conversationIds?.userId ?? '',
      }
    );
    return Promise.resolve(response);
  }
}
